{%extends "player_base.html"%}
{%block onload%}{{ block.super }}update_friends();{%endblock%}
{%block title%}Player Setup{%endblock%}

{%block update_friends%}
{{ block.super }}
  // var friends_table = clear_firends_table()
  // var loading_row = friends_table.insertRow(1);
  // loading_row.innerHTML = '<td colspan=3>Loading...</td>';
  dao('friends', 'list', null, finish_update_friends, alert);
{%endblock%}

{%block body%}
{{ block.super }}
<script>

function friend_remove_button(alias, friend_id, pending) {
  var result = "<button onClick='remove_friend(\"" +
      alias + "\", \"" +
      friend_id + "\");'>X</button>";
  if (pending) {
    result = "<table cellspacing=0><tr><td>" +
        "<button onClick=\"dao('friends', 'accept', 'friend_id=" + friend_id + "', update_friends, alert);\">&#10003;</button>" +
        "</td><td>" + result + "</td></tr></table>";
  }
  return result
}

function clear_firends_table() {
  var friends_table = document.getElementById('friendsTable');
  while (friends_table.rows.length > 1) {
    friends_table.deleteRow(1)
  }
  return friends_table
}

function remove_friend(alias, friend_id) {
  if (confirm('Are you sure you remove "' + alias + '"?')) {
    dao('friends', 'remove', 'friend_id=' + friend_id, null, alert);
  }
}

function finish_update_friends(txt) {
  var friends_table = clear_firends_table()
  friends = txt.split(',');
  for (var i = friends.length - 1; i >= 0 ; --i) {
    if (friends[i]) {
      row = friends_table.insertRow(1);
      data = friends[i].split('|');
      row.insertCell(0).innerHTML = data[0];
      row.insertCell(1).innerHTML = data[1];
      row.insertCell(2).innerHTML = friend_remove_button(data[0], data[2], data[3] == '0');
    }
  }
  if (friends_table.rows.length <= 1) {
    friends_table.insertRow(1).innerHTML = '<td colspan=3>None</td>';
  }
}

function clear_email(msg) {
  document.getElementById('new_email').value = '';
}

function add_friend() {
  var email = document.getElementById('new_email');

  if (email.value) {
    dao('friends', 'add', 'email=' + email.value, update_friends, alert, clear_email);
  }
}

function update_player() {
  alias = document.getElementById('alias').value;
  dao('player', 'update', 'alias=' + alias, null, alert);
}

//-->
</script>
<center>
<h2>Player Settings:</h2>
<table>
  <tr>
    <td>Alias</td>
    <td><input id='alias' type=text onKeyPress='on_enter(event, update_player);' value='{{ alias }}'/></td>
  </tr>
  <tr><td colspan=2 align="center"><button onClick='update_player();'>Update</button></td></tr>
</table>

<h2>Friends:</h2>
<table id='friendsTable' class="round">
  <tr><th>Alias</th><th>E-mail</th><th width="20"></th></tr>
</table>
<br/>
<table>
  <tr>
    <th>E-mail</th>
    <td><input id='new_email' type=text onKeyPress='on_enter(event, add_friend);'/></td>
    <td><button onClick='add_friend();'>Add</button></td>
  </tr>
</table>
</center>
{%endblock%}
